# -*- encoding: utf-8 -*-

"""
@File:      tc_libtdb_libtdb_func_002.py.py
@Time:      2024/04/17 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libtdb_libtdb_func_002.py.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libtdb libtdb-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >ltdb_test2.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <tdb.h>
#include <fcntl.h>
#include <string.h>

int main() {
    struct tdb_context *tdb;
    TDB_DATA key, data;

    // 尝试创建新的数据库文件
    tdb = tdb_open("ltdb_test2.tdb", 0, TDB_DEFAULT | TDB_VOLATILE, O_RDWR | O_CREAT | O_TRUNC, 0600);
    if (tdb == NULL) {
        fprintf(stderr, "创建数据库失败\\n");
        exit(EXIT_FAILURE);
    }

    // 关闭数据库文件
    tdb_close(tdb);

    // 重新打开刚才创建的数据库文件
    tdb = tdb_open("ltdb_test2.tdb", 0, TDB_DEFAULT, O_RDWR, 0600);
    if (tdb == NULL) {
        fprintf(stderr, "打开数据库失败\\n");
        exit(EXIT_FAILURE);
    }

    // 尝试添加一个键值对用于测试
    key.dptr = (unsigned char *)"test_key";
    key.dsize = strlen("test_key") + 1;
    data.dptr = (unsigned char *)"test_value";
    data.dsize = strlen("test_value") + 1;

    if (tdb_store(tdb, key, data, TDB_INSERT) != 0) {
        fprintf(stderr, "键值对添加失败\\n");
        tdb_close(tdb);
        exit(EXIT_FAILURE);
    }

    // 再次关闭数据库文件
    tdb_close(tdb);
    
    printf("所有操作执行完毕\\n");

    return 0;
}
EOF'''
        self.cmd(cmdline)


    def test(self):
        self.cmd("gcc -o ltdb_test2 ltdb_test2.c -ltdb")
        code, ltdb_result = self.cmd("./ltdb_test2")
        self.assertIn('所有操作执行完毕', ltdb_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf ltdb_test2.c ltdb_test2 ltdb_test2.tdb")
